<template>
    <div class="app-container">
        <el-link style="font-size: 20px;margin: 0 0 10px 20px;" :underline="false" target="_blank">培训结果录入</el-link>
        <el-form  ref="updForm">
            <!-- <el-form-item label="培训内容" prop="userName" label-width="150px">
                <el-select 
                     v-model="form.trainingContent" 
                     clearable      
                     filterable
                     style="width: 230px"
                     placeholder="请选择培训内容"
                     @change="contentChange"
                     class="ul-item">
                     <el-option :value="item.trainingContent" :label="item.trainingContent" v-for="(item,index) in this.trainLsit" :key="index"/>
                </el-select>
            </el-form-item> -->
            <el-form-item label="培训人员" prop="userName" label-width="150px">
                <!-- <el-select 
                     v-model="form.userName" 
                     clearable      
                     filterable
                     style="width: 200px"
                     placeholder="请选择培训人员"
                     @change="contentChange"
                     class="ul-item">
                     <el-option :value="item.userName" :label="item.userName" v-for="(item,index) in this.getUserList" :key="index"/>
                </el-select> -->
                <el-input v-model="form.userName" class="ul-item" disabled autosize  style="width: 200px"/>
            </el-form-item>
                <div style="display: flex;margin: 30px 0 0px 50px;">
                    <el-form-item label="培训照片" prop="trainingAttendanceSheet"  label-width="100px" style="margin-right: 40px;">
                        <el-upload
                          class="upload-demo"
                          action="http://192.168.3.11:8086/technologyFile"
                          :on-success="handlePdfSuccess1"
                          :on-remove = "removePdf1"  
                          :on-change= "pdfRemove"
                          :headers="getHttpHeader"
                          :before-upload="beforeFilsUploadImg"
                          :limit="1"
                          :file-list="fileList1"
                          style="width: 150px;">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="培训签到表" prop="trainingAttendanceSheet"  label-width="100px">
                        <el-upload
                          class="upload-demo"
                          action="http://192.168.3.11:8086/technologyFile"
                          :on-success="handlePdfSuccess2"
                          :on-remove = "removePdf2"
                          :on-change= "pdfRemove"
                          :headers="getHttpHeader"
                          :before-upload="beforeFilsUpload"
                          :limit="1"
                          :file-list="fileList2"
                          style="width: 150px;">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </div>
            </el-form>
            <el-dialog  
              :title="title"
              :visible.sync="showAdd"
              @close="closeShow"
              width="65%"
            >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
                <div style="display: flex;">
                    <el-form-item label="姓名" prop="userName"  label-width="80px" >
                        <el-input disabled placeholder="请输入姓名" clearable v-model.trim="createForm.userName" class="ul-item" style="width: 100px"/>
                    </el-form-item>
                    <el-form-item label="工号" prop="jobNumber"  label-width="80px" >
                        <el-input disabled placeholder="请输入工号" clearable v-model.trim="createForm.jobNumber" class="ul-item" style="width: 100px"/>
                    </el-form-item>
                    <el-form-item label="签到" prop="trainSignIn" label-width="80px" >    
                          {{ '否 ' }}<el-switch  v-model="createForm.trainSignIn" active-value="1" inactive-value="0" />{{ ' 是' }}
                    </el-form-item>
                    <el-form-item label="考核方式" prop="evaluationMode" label-width="80px" >
                       <el-input disabled v-model="createForm.evaluationMode" placeholder="请选择考核方式" autosize style="width: 150px"/>
                    </el-form-item>
                    <el-form-item label="考核内容" prop="trainingContent" label-width="120px" >
                       <el-input disabled v-model="createForm.trainingContent" autosize style="width: 150px"/>
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="考核得分" prop="examinationScore" label-width="80px" >
                        <el-input placeholder="请输入考核得分" clearable v-model.number="createForm.examinationScore" type="number" class="ul-item"/>
                    </el-form-item>
                
                    <el-form-item label="考核人员" prop="assessorJobNumber" v-if="createForm.trainSignIn != 0" label-width="80px" >
                      <el-select style="width: 150px;" clearable filterable v-model="createForm.assessorJobNumber" placeholder="考核人员" @focus="getuserList" class="ul-item">
                        <el-option :value="item.jobNumber" :label="item.userName" v-for="(item,index) in this.userList" :key="index"/>
                      </el-select>
                      <!-- <el-input v-model="createForm.assessorJobNumber" placeholder="请选择考核方式" autosize style="width: 150px"/> -->
                    </el-form-item>
                      
                    <el-form-item v-if="createForm.trainSignIn != 0" label="考核记录" prop="assessmentData" label-width="80px" >
                          <el-upload
                            class="upload-demo"
                            action="http://192.168.3.11:8086/technologyFile"
                            :on-success="handlePdfSuccess3"
                            :on-remove = "removePdf3"  
                            :on-change= "pdfRemove"
                            :headers="getHttpHeader"
                            :before-upload="beforeFilsUpload"
                            :limit="1"
                            :file-list="fileList3">
                            <el-button size="small" type="primary">点击上传</el-button>
                          </el-upload>
                          <!-- <el-input v-model="createForm.assessmentData" type="textarea"/> -->
                      </el-form-item>
                      
                      <el-form-item label="效果评价" v-if="createForm.trainSignIn != 0" prop="effectivenessEvaluation" label-width="80px" >
                      <el-select
                          v-model="createForm.effectivenessEvaluation"
                          placeholder="请选择效果评价"
                          class="ul-item"
                          filterable
                          clearable>
                          <el-option
                              v-for="(item,index) in this.effectivenessEvaluationList"
                              :key="index"
                              :label="item"
                              :value="item">
                          </el-option>
                      </el-select>
                    </el-form-item>
                </div>
              
           <div>
                <el-link :underline="false" type="danger">备注: 分数必填项, 未签到直接填写65分一下(需重新培训)</el-link>
            </div>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >确认</el-button
            >
        </div>
    </el-dialog>
    <div>
        <el-link :underline="false" type="danger">备注1: 填写考核结果前必须先上传以上培训照片和签到表照片</el-link>
    </div>
    <div>
        <el-link :underline="false" type="danger">备注2: 填写信息后必须点击保存按钮才会生效！！</el-link>
    </div>
    <div style="display: flex; justify-content:space-between">
        <!-- <div style="font-size: 20px;margin: 0 0 0 20px;">培训人员信息</div> -->
        <el-link style="margin: 0 0 0 20px;" :underline="false" target="_blank">培训人员信息</el-link>
        <el-button type="success" @click="submitFinish" :loading="saveLoading" size="medium" style="margin-right: 200px;">保 存</el-button>
    </div>
            <el-table  :data="tableInfo" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
            <el-table-column  label="序号" type="index" align="center" width="80px"/>
            <el-table-column label="姓名"  prop="userName" align="center"/>
            <el-table-column label="工号"  prop="jobNumber" align="center"/>
            <el-table-column label="培训类别"  prop="trainingCategory" align="center"/>
            <el-table-column label="培训内容"  prop="trainingContent" align="center"/>
            <el-table-column label="考核方式"  prop="evaluationMode" align="center"/>   
            <el-table-column label="签到"  prop="trainSignIn" align="center">
                <template slot-scope="scope" >
                      {{ scope.row.trainSignIn == 1 ? '已签到' : scope.row.trainSignIn == 0 ? '未到' : '-' }}
                  </template>
            </el-table-column>
            <el-table-column label="考试成绩"  prop="examinationScore" align="center"/>
            <el-table-column label="考核人员"  prop="assessorJobNumber" align="center"/>
            <el-table-column label="效果评价"  prop="effectivenessEvaluation" align="center"/>
            <el-table-column label="考核结果"  prop="evaluationResult" align="center"/>
            <el-table-column label="考核记录"  prop="assessmentData" align="center">
                <template slot-scope="scope" >  
                  <el-link style="font-size: 12px" :href="scope.row.assessmentData" target="_blank">{{scope.row.assessmentData}}</el-link>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="180">
                  <template slot-scope="scope" >
                      <div class="fx" style="display: flex">
                          <el-button size="mini" type="primary" @click="handleEdit(scope.row,scope.$index)">填写</el-button>
                          <!-- <el-button
                              icon="el-icon-delete"
                              class="el-button el-button--danger"
                              style="font-size: 15px;"
                              @click="handleDelete(scope.row,scope.$index)"
                          ></el-button> -->
                      </div>
                  </template>
            </el-table-column>
        </el-table> 
    </div>
</template>

<script>
import { recordFind,findByUser,recordUpd,transferGet,updUserKnowledgeRecordState,recordUpdList } from "@/api/knowledgeSkill"
import { findUserListGroup} from '@/api/chargingData'

import mixin from '@/utils/mixin.js'
export default {
    name: 'training_results',
    mixins: [mixin],
    data () {   
        return {
            form:{},
            contentLsit:[],
            createForm:{},
            userList:[],
            getHttpHeader: {                    //上传文件的头
                Authorization: '',              //传输文件的token
                CHECK_USER_VALUE: 'GOLWAY',
                CHECK_PASSWORD_VALUE: '8D4DD3F80CEB6149329FDBD590B164F1'
            },
            addRules: {
                userName: [
                    { required: true, message: "姓名不能为空!", trigger: "change" },
                ],
                jobNumber: [
                    { required: true, message: "工号不能为空!", trigger: "change" },
                ],
                trainSignIn: [
                    { required: true, message: "签到不能为空!", trigger: "change" },
                ],
                evaluationMode: [
                    { required: true, message: "考核方式不能为空!", trigger: "change" },
                ],
                examinationScore: [
                    { required: true, message: "考核得分不能为空!", trigger: "change" },
                ],
                assessorJobNumber: [
                    { required: true, message: "考核人员不能为空!", trigger: "change" },
                ],
                effectivenessEvaluation: [
                    { required: true, message: "效果评价不能为空!", trigger: "change" },
                ],
                assessmentData: [
                    { required: true, message: "考核记录不能为空!", trigger: "change" },
                ],
            },
            fileList1:[],  
            fileList2:[],  
            fileList3:[],
            name:'',
            tableInfo:[],
            showAdd: false,
            title: '修改',
            effectivenessEvaluationList:['A','B','C','D'],
            evaluationModeLs: ['理论考核','实操考核'],
            rowIndex:'',
            getUserList:[],
            idArr:[],            // 所有岗位id
            trainingCategory:'',
            trainLsit:[],
            queryArr:[], // 提交填写的部分
            saveLoading: false,
            souceType:''
        }
    },
    computed: {
    },
    methods: {
        closeShow(){
            this.$refs.createForm.resetFields()
            this.fileList3 = []
            this.showAdd = false
        },
         // 获取个人信息
         async getuserList(e){
            let query = {page:1,limit:9999,status: 1}
            const {data} = await findUserListGroup(query)
            this.userList = data
        },
        // 最终提交
        async submitFinish(){
            if(!this.tableInfo.length) return this.$message.error('没有培训人员信息！')
            if(!this.form.trainingAttendanceSheet) return this.$message.error('培训照片不能为空！')
            if(!this.form.trainingPhoto) return this.$message.error('签到表照片不能为空！')
            for(const item of this.tableInfo){
               if(!item.evaluationResult) return this.$message.error('培训人员信息请填写完整！')
            }
            this.tableInfo.forEach(async item =>{
                item.assessmentTime = this.setNowTime()
                item.trainingAttendanceSheet = this.form.trainingAttendanceSheet
                item.trainingPhoto = this.form.trainingPhoto
            })
            this.queryArr = this.tableInfo
            // this.queryArr = this.tableInfo.filter(item => item.examinationScore)
            this.queryArr.forEach(async item1 =>{
                let State = ''
                console.log(this.trainingCategory)
                if(this.trainingCategory == '入职培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        State = 2
                    }else{
                        State = 0
                    }
                }else if(this.trainingCategory == '岗前培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        // if(item1.type == 111){
                        //     State = '结束'
                        // }else{
                            State = 4
                        // }
                    }else{
                        State = 2
                    }
                }else if(this.trainingCategory == '岗位培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        if(item1.type == 22 || item1.type == 222 || item1.type == 111){
                            State = '结束'
                        }else{
                            State = 6
                        }
                    }else{
                        State = 4
                    }
                }else if(this.trainingCategory == '专业培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        State = '结束'
                    }else{
                        State = 4
                    }
                }else if(this.trainingCategory == '关键工序培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        State = 4
                    }else{
                        State = 2
                    }
                }else if(this.trainingCategory == '岗位案例培训'){
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        if(item1.type == 22 || item1.type == 222){  // 晋级管理
                            State = '结束'
                            // State = 2
                        }else{
                            State = 6
                        }
                    }else{
                        if(item1.type == 22 || item1.type == 222){
                            State = 2
                        }else{
                            State = 4
                        }
                    }
                }else if(this.trainingCategory == '岗位实操培训'){   // 工序页面
                    if(item1.evaluationResult && item1.evaluationResult != '不合格'){
                        State = 8
                    }else{
                        State = 6
                    }
                }
                if(this.souceType = '岗位培训'){
                    this.getUserList.forEach(async item2 =>{
                        if(item2.jobNumber == item1.jobNumber){
                            await updUserKnowledgeRecordState({id:item2.id,userKnowledgeJobTransferState:State})
                        }
                    })
                }
                item1.state = State
            })
            console.log('queryArr',this.queryArr)
            this.saveLoading = true
            const data = await recordUpdList({objectMap: this.queryArr})
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.$router.back();
            console.log(this.idArr)
            console.log(this.queryArr)
            this.saveLoading = false
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        async submitprocess(){
            // if(!this.form.trainingAttendanceSheet || !this.form.trainingPhoto) return this.$message.error('请上传培训照片或签到照片！')
            if(this.createForm.effectivenessEvaluation == 'A'){
                    this.createForm.trainingResults = '优秀'
                }else if(this.createForm.effectivenessEvaluation == 'B'){
                    this.createForm.trainingResults = '良好'
                }else if(this.createForm.effectivenessEvaluation == 'C'){
                    this.createForm.trainingResults = '合格'
                }else if(this.createForm.effectivenessEvaluation == 'D'){
                    this.createForm.trainingResults = '不合格'
                }
            if(this.createForm.examinationScore >= 85){
                this.createForm.evaluationResult = '优秀'
            }else if(this.createForm.examinationScore >= 75){
                this.createForm.evaluationResult = '良好'
            }else if(this.createForm.examinationScore >= 65){
                this.createForm.evaluationResult = '合格'
            }else if(this.createForm.examinationScore < 65){
                this.createForm.evaluationResult = '不合格'
            }
            // console.log(this.createForm)
            this.$set(this.tableInfo[this.rowIndex],'examinationScore',this.createForm.examinationScore)
            this.$set(this.tableInfo[this.rowIndex],'assessorJobNumber',this.createForm.assessorJobNumber)
            this.$set(this.tableInfo[this.rowIndex],'trainSignIn',this.createForm.trainSignIn)
            this.$set(this.tableInfo[this.rowIndex],'effectivenessEvaluation',this.createForm.effectivenessEvaluation)
            this.$set(this.tableInfo[this.rowIndex],'assessmentData',this.createForm.assessmentData)
            this.$set(this.tableInfo[this.rowIndex],'evaluationResult',this.createForm.evaluationResult)
            this.$set(this.tableInfo[this.rowIndex],'trainingResults',this.createForm.trainingResults)
            this.showAdd = false
        },
        handleEdit(row,index){
            this.rowIndex = index
            if(row.assessmentData){
                this.fileList3.push({name: 'food.jpeg', url: row.assessmentData})
            }
            this.createForm = Object.assign({},row) 
            this.showAdd = true
        },
        // 培训内容改变
        async contentChange(){
            let query = {
                page:1,
                limit:1000,
                userName:this.form.userName,                     // 培训内容
                trainingCategory:this.trainingCategory,  // 培训类别
                souceType:this.souceType                // 来源类型
            }
            const res = await recordFind(query)
            console.log(res.data.list)
            // 筛选出没有培训结果的
            let evaluationResult = res.data.list.filter(item => !item.evaluationResult)  
            // let evaluationResult = res.data.list
            // 筛选出只有get接口或者当前在执行的履历 里面有的工号相同
            console.log('evaluationResult',evaluationResult )
            console.log(this.getUserList)
            let commonElements = evaluationResult.filter(item1 => this.getUserList.some(item2 => item2.jobNumber == item1.jobNumber))
            this.idArr = []
            this.getUserList.forEach(item1 =>{
                if(commonElements.some(item2 => item2.jobNumber == item1.jobNumber)){
                    this.idArr.push({id:item1.id,jobNumber:item1.jobNumber})   // 拿到对应的id和工号  点击保存传节点流程用
                }
            })
            // console.log(this.idArr) 
            this.tableInfo = commonElements
            if(!this.tableInfo.length) return this.$message.error('该人员资料以维护完成！')
        },
         // 上传PDF文档成功回调函数
         handlePdfSuccess1(response) {
          this.form.trainingPhoto = response.results
        },
         // 上传PDF文档成功回调函数
         handlePdfSuccess2(response) {
          this.form.trainingAttendanceSheet = response.results
        },
         // 上传PDF文档成功回调函数
         handlePdfSuccess3(response) {
          this.createForm.assessmentData = response.results
        },
        async removePdf1(file) {
          return this.form.trainingPhoto = ''
        },
        async removePdf2(file) {
          return this.form.trainingAttendanceSheet = ''
        },
        async removePdf3(file) {
          return this.createForm.trainingPhoto = ''
        },
        pdfRemove(e){
            if(e.status == 'fail') return this.$message.error("文件上传失败!")
            else if(e.status == 'success') return this.$message.success("文件上传成功!")
        },
        // 文件上传之前的函数，将token传入头中
        beforeFilsUploadImg(file) {
            this.getHttpHeader.Authorization = this.dealCookie()
        },
        beforeFilsUpload(file) {
            // 检查文件类型是否为 PDF
            const isPDF = file.type === 'application/pdf';
            if (!isPDF) {
               this.$message.error('只能上传 PDF 格式的文件！');
            }
            this.getHttpHeader.Authorization = this.dealCookie()
            return isPDF
        },
        // cookies的处理函数
        dealCookie() {
            const strcookie = document.cookie                     //获取cookie字符串
            const arrcookie = strcookie.split("; ")               //分割
            for ( var i = 0; i < arrcookie.length; i++) {
                const arr = arrcookie[i].split("=")
                if (arr[0] == "agent_Authorization") {
                    return arr[1]
                }
            }
            return ""
        },
        setNowTime() {
            let date = new Date()
            // 获取年、月、日、时、分、秒  
            const year = date.getFullYear();  
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
            const day = String(date.getDate()).padStart(2, '0');  
            const hour = String(date.getHours()).padStart(2, '0');  
            const minute = String(date.getMinutes()).padStart(2, '0');  
            const second = String(date.getSeconds()).padStart(2, '0');  
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;   
        },
        async handleFilter(){
            console.log('query', this.$route.query)
            this.trainingCategory = this.$route.query.trainingCategory
            this.souceType = this.$route.query.souceType
            this.form.userName = this.$route.query.name
            let query = { 
                noState:'结束'
            }
            if(this.$route.query.type){
                if(this.$route.query.type == '入职'){  
                    query.type = '1,11,111,1111'   // 从入职与培训 进来
                }else if(this.$route.query.type == '晋级'){
                    query.type = '2,22,222'       // 从晋级管理 进来
                }else if(this.$route.query.type == '关键工序'){
                    query.type = '4'       // 从关键工序管理 进来
                }
                const res = await findByUser(query)
                this.getUserList = res.data.list
            }else {
                const res = await transferGet()
                this.getUserList = res.data
            }
            this.contentChange()
            console.log(this.getUserList)
        }
    },  
    // watch: {
    //   '$route'(to, from) {
    //     // 重置组件状态 
    //     this.handleFilter();
    //   }
    // },
   async mounted() {
    this.handleFilter()
    }
}
</script>

<style>
.app-container{
    margin: 10px;
}
</style>
